import {app, BrowserWindow, ipcMain, shell} from 'electron'
import { setupDbHandlers, removeDbHandlers } from './dbHandlers'

/**
 * 判断是否是开发模式
 */
export const isDev = process.env.NODE_ENV === 'development' || !!process.env.VITE_DEV_SERVER_URL

/**
 * 设置开发模式IPC处理程序
 */
function setupDevHandlers() {
  if (!isDev) return

  // 重新加载窗口
  ipcMain.on('dev:reload', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) win.webContents.reload()
  })

  // 切换开发者工具
  ipcMain.on('dev:toggleDevTools', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) win.webContents.toggleDevTools()
  })
}

/**
 * 设置所有IPC处理程序
 */
export function setupIpcHandlers() {
  // 窗口控制
  ipcMain.on('app:minimize', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) win.minimize()
  })

  ipcMain.on('app:maximize', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) {
      if (win.isMaximized()) {
        win.unmaximize()
      } else {
        win.maximize()
      }
    }
  })

  ipcMain.on('app:close', () => {
    const win = BrowserWindow.getFocusedWindow()
    if (win) win.close()
  })

  // 系统信息
  ipcMain.handle('app:getInfo', () => {
    return {
      appName: app.getName(),
      appVersion: app.getVersion(),
      platform: process.platform,
      arch: process.arch
    }
  })

  ipcMain.on('open:external', (_, url: string) => {
    shell.openExternal(url)
  })

  // 设置数据库处理程序
  setupDbHandlers()

  // 设置开发模式处理程序
  setupDevHandlers()
}

/**
 * 移除所有IPC处理程序
 */
export function removeIpcHandlers() {
  // 窗口控制
  ipcMain.removeAllListeners('app:minimize')
  ipcMain.removeAllListeners('app:maximize')
  ipcMain.removeAllListeners('app:close')
  ipcMain.removeHandler('app:getInfo')

  // 移除数据库处理程序
  removeDbHandlers()

  // 开发模式
  if (isDev) {
    ipcMain.removeAllListeners('dev:reload')
    ipcMain.removeAllListeners('dev:toggleDevTools')
  }
}
